import * as vscode from 'vscode';
import axios from 'axios';

// 导出解释代码的函数
export function registerExplainCodeCommand(context: vscode.ExtensionContext) {
  const disposable = vscode.commands.registerCommand(
    'cw-vscode-ai.explainCode',
    async (text: string, uri: string, range: vscode.Range) => {
      console.log('explainCode 命令被触发', { text: text?.substring(0, 20) + '...', uri, range });
      
      // 验证参数
      if (!text) {
        vscode.window.showErrorMessage('没有提供要解释的代码内容');
        return;
      }
      
      try {
        // 显示进度指示器
        await vscode.window.withProgress(
          {
            location: vscode.ProgressLocation.Notification,
            title: '正在分析代码...',
            cancellable: false,
          },
          async (progress) => {
            try {
              console.log('进度通知已创建');
              progress.report({ increment: 0, message: '准备中...' });
              
              // 确保在UI更新后再继续
              await new Promise(resolve => setTimeout(resolve, 100));
              
              progress.report({ increment: 30, message: '正在发送请求...' });
              console.log('发送API请求');

              // API 请求代码
              const response = await axios.post(
                'http://47.122.123.198:8088/v1/chat-messages',
                {
                  inputs: {},
                  query: `解释代码:\n${text}`,
                  conversation_id: '',
                  user: 'abc-123',
                  files: '',
                },
                {
                  headers: {
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer app-5KVLxDJ1OZ4bxGcakQMB9ffN',
                  },
                }
              );

              console.log('收到API响应');
              
              // 获取解释
              const explanation = response.data.answer || '无法获取代码解释';
              progress.report({ increment: 70, message: '正在处理响应...' });

              // 创建和显示 Webview
              const panel = vscode.window.createWebviewPanel(
                'codeExplanation', 
                '代码解释', 
                vscode.ViewColumn.Beside,
                {
                  enableScripts: true,
                  retainContextWhenHidden: true,
                }
              );

              // 设置 HTML 内容
              panel.webview.html = `
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>代码解释</title>
                    <style>
                        body { font-family: Arial, sans-serif; padding: 20px; }
                        pre { background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto; }
                        .code-block { margin-bottom: 20px; }
                        .explanation { line-height: 1.6; }
                    </style>
                </head>
                <body>
                    <h2>原始代码</h2>
                    <div class="code-block">
                        <pre>${escapeHtml(text)}</pre>
                    </div>
                    <h2>代码解释</h2>
                    <div class="explanation">
                        ${explanation.replace(/\n/g, '<br>')}
                    </div>
                </body>
                </html>
              `;
              
              progress.report({ increment: 100, message: '完成！' });
            } catch (error: any) {
              console.error('解释代码失败:', error);
              vscode.window.showErrorMessage(`解释代码失败: ${error.message}`);
            }
          }
        );
      } catch (progressError: any) {
        console.error('创建进度条失败:', progressError);
        vscode.window.showErrorMessage(`无法创建进度指示器: ${progressError.message}`);
      }
    }
  );

  // 返回 disposable 以便在 extension.ts 中添加到 context.subscriptions
  return disposable;
}

// 辅助函数：转义HTML
function escapeHtml(text: any) {
  if (typeof text !== 'string') {
    console.warn('escapeHtml 接收到非字符串值:', text);
    text = String(text || '');
  }
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}